package com.xiaoxx.common.intercepter;

import com.xiaoxx.common.base.JwtUser;
import com.xiaoxx.common.error.ErrorException;
import com.xiaoxx.common.result.R;
import com.xiaoxx.common.result.RType;
import com.xiaoxx.enums.ResdisKeyEnum;
import com.xiaoxx.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author :HX
 * @date : 2023/7/19
 */
public class AdminInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        JwtUser jwtUser = JwtUtil.getJwtUser(request);
        //校验是否其他账号登录
        String token = request.getHeader("Authorization");
        String redisToken = redisTemplate.opsForValue().get(ResdisKeyEnum.LOGIN_TOKEN.getRedisPath().concat(jwtUser.getUserId()));
        if (!StringUtils.hasLength(redisToken)) {
            throw new ErrorException(RType.AUTHORITY_LOGIN_EXPIRED);
        }
        if (!token.equals(redisToken)) {
            throw new ErrorException(RType.AUTHORITY_LOGIN_EXPIRED);
        }
        //普通鉴权
        R<JwtUser> jwtUserR = JwtUtil.getJwtUserR(request, response);
        //鉴权
        if (!jwtUserR.getCode().equals(RType.SYS_SUCCESS.getValue())) {
            throw new ErrorException(jwtUserR.getCode(), jwtUserR.getMsg());
        }
        return true;
    }

    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
